<template>
  <div :style="{width: '100%', height: '100%'}">
    <video ref="videoPlay" muted autoplay controls style="width: 100%; height: 100%" @click="fullScreen"></video>
  </div>
</template>

<script setup name="CameraFlvVideo">

import mpegts from 'mpegts.js'
import { connect, disConnect, keepLive } from '@/api/coal/stream';

const props = defineProps({
  deviceId: {
    type: Number,
    default: null,
  },
})
const { proxy } = getCurrentInstance();
const route = useRoute();

const videoPlay = ref(null)
const flvPlayer = ref(null)
let keepLiveInterval = ref<String>("");

onMounted(() => {
  nextTick(() => {
    createVideo()
  })
  keepLiveInterval = setInterval(()=>{
    keepLive(props.deviceId).then(resp=>{})
  },1000*60*10)
})

function createVideo() {
  connect(props.deviceId).then(resp=>{
    if (mpegts.isSupported()) {
      flvPlayer.value = mpegts.createPlayer(
          {
            type: 'flv',
            url: resp.msg, //你的拉流rtmp或者http等地址
            isLive: true,
            hasAudio: false,
            cors: true
          },
          {
            enableWorker: false, // 不启用分离线程
            enableStashBuffer: false, // 关闭IO隐藏缓冲区
            reuseRedirectedURL: true, // 重用301/302重定向url，用于随后的请求，如查找、重新连接等。
            autoCleanupSourceBuffer: true, // 自动清除缓存
            autoCleanupMaxBackwardDuration: 3*60,
            autoCleanupMinBackwardDuration: 2*60,
            fixAudioTimestampGap: false
          }
      )
      flvPlayer.value.attachMediaElement(videoPlay.value);
      flvPlayer.value.load();
      let isPlaying = flvPlayer.value.currentTime > 0 && !flvPlayer.value.paused && !flvPlayer.value.ended && flvPlayer.value.readyState > 2;
      if (!isPlaying) {
        let playPromise = flvPlayer.value.play()
        if (playPromise !== undefined) {
          playPromise.then(() => {
            flvPlayer.value.play();
          }).catch(()=> {

          })
        }
      }
      flvPlayer.value.on(mpegts.Events.ERROR, (errType, errDetail) =>{
        console.log('errorType:', errType)
        console.log('errorDetail:', errDetail)
        if (flvPlayer.value) {
          destroyVideo()
          createVideo()
        }
      })
    }
  })
}

function fullScreen(){
  if (videoPlay.value.requestFullscreen){
    videoPlay.value.requestFullscreen()
    videoPlay.value.play()
  } else if (videoPlay.value.mozRequestFullscreen){
    videoPlay.value.mozRequestFullscreen()
    videoPlay.value.play()
  }else if (videoPlay.value.webkitRequestFullscreen){
    videoPlay.value.webkitRequestFullscreen()
    videoPlay.value.play()
  }
}
function destroyVideo(){
  if(!flvPlayer.value) return
  flvPlayer.value.pause()
  flvPlayer.value.unload()
  flvPlayer.value.detachMediaElement()
  flvPlayer.value.destroy()
  flvPlayer.value = null
}

onActivated(()=>{
  flvPlayer.value.play();
})

onDeactivated(()=>{
  //console.log("缓存组件停用时调用")
})

onBeforeUnmount(() => {
  destroyVideo()
  keepLiveInterval && clearInterval(keepLiveInterval)
  /*disConnect(props.deviceId).then(resp=>{
  })*/
})
</script>
